<?php
class AppController extends Controller {
    var $components   = array('Auth', 'Session', 'Captcha');
    var $helpers      = array('Html', 'Form', 'Javascript', 'Time');
    var $paginate     = array('limit' => MAX_ROWS, 'page' => 1);
    var $modelName;
    
    function beforeFilter() {
        // modelName is available to view
        $this->modelName =  Inflector::Singularize($this->name);
        $this->set( 'modelName', $this->modelName );
        
        $action = strtolower($this->params['action']);
        $controller = strtolower($this->params['controller']);
        $this->set('action', $action);
        $this->set('controller', $controller);
        
        // profile of users available to all views
        $profile = '';
        if ( $this->Auth->user('id') ) {
            $showProfile = true;
            $profile = $this->Auth->user();
            $profile = $profile['User'];
        }
        $this->set('profile', $profile);
        
        // form
        if ($action == 'add' || $action == 'edit') {
            // make sure created_by & modified by fields are filled, if table has that fields
            if ( !empty($this->data) ) {
                if ($this->{$this->modelName}->checkByField() ) {
                    if ($action == 'add') {
                        $this->data[$this->modelName]['created_by'] = $this->Auth->user('id');
                    } else if ($action == 'edit') {
                        $this->data[$this->modelName]['modified_by'] = $this->Auth->user('id');
                    }
                }
            }
        }
        
        // build menus
    }
   
/**
 * These are common action used by ebox controller
 * Inherited to all subclass controller, can be overiden
 * by writing same method name on controller class.
 * Their views are placed in app/views/common
 *  
 * gedex
 */
    
    // index for common tablegrid
    function index() {
        if ( isset($this->params['url']['ajax']) && $this->params['url']['ajax'] ) {
            Configure::write('debug', 0);
            $this->layout = 'ajax';
        }
        $this->__index();
		$this->set('formgrid', Helper::url('delete_rows'));
    }
    
    function __index() {
        $condition = array();
        $str_fl = '';
        
        if ( isset($this->params['url']['search']) && $this->params['url']['search'] == 'Search' ) {
            App::import('Sanitize');
            $filtered_link   = array();
            $filtered_link[] = '?search=Search';
            
            foreach ( $this->params['url'] as $param => $value ) {
                if ( !empty($value) && $param != 'url' && $param != 'search' && $param != 'ref') {
                    $filtered_link[] = $param . "=" . $value;
                    $this->set($param . "Value", $value);
                    $like = str_replace('*', '%', Sanitize::paranoid($value, array('*', ' ', '-')));
                    $condition[$this->modelName.".$param LIKE"] = $like;
                }
            }
            
            if (!empty($filtered_link)) {
                $str_fl = implode("&", $filtered_link);
            }   
        }
        
        $this->set('str_fl', $str_fl);
        $this->set('records', $this->paginate($condition));
    }
    
    function add() {
		$this->__add();
	}
    
    function __add() {
		if ( !empty($this->data) ) {
			$this->{$this->modelName}->create();
			$messageFlashSuccess = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __('successfully added', true);
			$messageFlashError = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __('cannot add this new record. Please fix the errors mentioned belows', true);
			if ($this->{$this->modelName}->save($this->data)) {
				$this->Session->setFlash( $messageFlashSuccess, 'success');
                $this->__redirect();
			} else {
                $this->Session->setFlash($messageFlashError, 'error');
			}
		}
	}
	
    function edit($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid parameter', true), 'error');
			$this->__redirect();
        }
        
		$this->set('id', $id);
        $this->__edit();
        
		if (empty($this->data)) {
			$this->data = $this->{$this->modelName}->find('first', array($this->modelName . '.id' => $id));
            
            if (!$this->data) {
                $this->Session->setFlash(__('Invalid parameter', true), 'error');
                $this->__redirect('index');
            }
		} else {
            $this->data[$this->modelName]['id'] = $id;
        }
	}
    
    function __edit() {
		if (!empty($this->data)) {
			$messageFlashSuccess = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __("successcully edited", true);
			$messageFlashError = (isset($this->niceName) ? $this->niceName : $this->modelName) . ' ' . __("cannot save this modification. Please fix the errors mentioned belows", true);
			
			if ($this->{$this->modelName}->save($this->data)) {
				$this->Session->setFlash( $messageFlashSuccess, 'success');
                $this->__redirect('index');
			} else {
                $this->Session->setFlash($messageFlashError, 'error');
            }
		}
    }
    
    // delete only one record, commonly found as a link in edit action
    function delete($id = null) {
		if ($this->{$this->modelName}->del($id)) {
            $this->Session->setFlash(__("Record successfully deleted", true), 'success');
		} else {
            $this->Session->setFlash(__("Error deleting deleted", true), 'error');
		}
        $this->redirect(array('action' => 'index'));
	}
	
	function __redirect() {
			$this->redirect(array('action' => 'index'));
	}
    
    // delete rows in tablegrid by checked checkbox
    function delete_rows() {
        $this->layout   = 'ajax';
        $this->viewPath = 'common';
        
        if ( Configure::read('debug') > 0 ) {
            Configure::write('debug', 0);
        }
    
		if ( !empty($this->data) ) {
		    $count = 0;
		    foreach ($this->data['rows'] as $row) {
		        if ( $this->{Inflector::singularize($this->name)}->del($row) ) {
		            $count++;
		        } else {
		            $this->set('result', '<div class="flash_box flash_success">' . __("Only", true) . ' ' . $count . ' ' . __("records can be deleted", true) . '</div>');
		        }
		    }
		    $this->set('result', '<div class="flash_box flash_success">' . "$count " . __("record succesfully deleted", true) . '</div>');
		} else {
		    // someone accessing the url
            $this->Session->setFlash('Invalid URL', 'error');
	        $this->redirect(array('action'=>'index'));
		}
	}
    
    function checkUnique() {
        $this->layout = 'ajax';
	    $this->viewPath = "common";
        
        if ( Configure::read('debug') > 0 ) {
            Configure::write('debug', 0);
        }
        
        if ( !$this->params['named'] ) {
	        $this->Session->setFlash('Invalid parameter', 'error');
	        $this->redirect(array('action'=>'index'));
	    }
        foreach ($this->params['named'] as $field => $value) {
            $condition[Inflector::singularize($this->name).".$field"] = $value;
	    }
        $result = $this->{Inflector::singularize($this->name)}->hasAny($condition);
	    $this->set('result', $result);
    }
	
	function jsonize() {
	    $this->layout = 'json/default';
	    $this->viewPath = "common";
	    
        if ( Configure::read('debug') > 0 ) {
            Configure::write('debug', 0);
        }
        
	    if ( !$this->params['named'] ) {
	        $this->Session->setFlash('Invalid parameter for JSON', 'error');
	        $this->redirect(array('action'=>'index'));
	    }
	    
	    foreach ($this->params['named'] as $field => $value) {
	        $like = str_replace('*', '%', $value);
            $condition[Inflector::singularize($this->name).".$field LIKE"] = $like;
	    }
        $this->{Inflector::singularize($this->name)}->recursive = -1;
	    $result = $this->{Inflector::singularize($this->name)}->findAll($condition);
	    $this->set('result', $result);
	}
    
    function __pathToController() {
        $plugin = isset($this->params['plugin']) ? $this->params['plugin'] . '/' : '';
        return $this->webroot . $plugin . $this->params['controller'];
    }
    
    function __setOption($model, $name, $options) {
        if (!isset($options['conditions'])) {
            $options['conditions'] = null;
        }
        
        $parentModel = Inflector::singularize($this->name);    
        if ( isset($this->$parentModel->$model) ) {
            $this->$parentModel->$model->recursive = -1;
            ${$name} = $this->$parentModel->$model->find('list', array('fields' => $options['fields'], 'conditions' => $options['conditions']));
        } else {
            App::import('Model', "Setup.$model");
            $this->$model = new $model;
            $this->$model->recursive = -1;
            ${$name} = $this->$model->find('list', array('fields' => $options['fields'], 'conditions' => $options['conditions']));
        }
        
        $this->set($name, ${$name});
    }
	
	function getOptions() {
		$this->cacheAction = true;
        $this->layout = 'json/default';
        
        if ( Configure::read('debug') > 0 ) {
            Configure::write('debug', 0);
        }
        
		$plugin = isset($this->params['url']['plugin']) ? $this->params['url']['plugin'] . '.' : '';
        $model = $this->params['url']['model'];
		$field = $this->params['url']['field'];
        $belongsTo = $this->params['url']['belongsTo'];
        $belongsToId = $this->params['url']['belongsToId'];
        
		$belongsTos = explode(',', $belongsTo);
		$belongsToIds = explode(',', $belongsToId);
		if (count($belongsTos) > 1 && count($belongsToIds) > 1) {
			$conditions = array();
			foreach ($belongsTos as $key => $bt) {
				$conditions[$model.'.'.$bt] =  $belongsToIds[$key];
			}
		} else {
			$conditions = array($model.'.'.$belongsTo => $belongsToId);
        }
		if ( isset($this->{$this->modelName}->$model) && !isset($this->$model) ) {
			$this->$model = $this->{$this->modelName}->$model;
		}
		if ( !isset($this->$model) ) {
	        App::import('Model', "$plugin$model");
	        $this->$model = new $model;
		}
        $this->$model->recursive = -1;
    
	    $result = $this->$model->find('list', array('fields' => array($model.'.id', $model.".$field"), 'conditions' => $conditions));
        
	    $this->set('result', $result);
    }

/**
 * Methods related to security
 */
    function securimage(){
        $this->layout = 'ajax'; //a blank layout
        
        if (Configure::read('debug') > 0) {
            Configure::write('debug', 0);
        }

        if ( isset($this->params['url']['audio']) && $this->params['url']['audio'] ) {
            $this->captcha->audio_format = (isset($_GET['format']) && in_array(strtolower($_GET['format']), array('mp3', 'wav')) ? strtolower($_GET['format']) : 'mp3');
            $this->set( 'captcha_data', $this->captcha->outputAudioFile() );
        } else {
            $this->set( 'captcha_data', $this->captcha->show('') ); //dynamically creates an image
        }
    }
}
?>
